<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" @submit.prevent>
        <el-form-item>
          <el-input v-model="queryParams.name" placeholder="分类名称" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" placeholder="状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增分类</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="categoryList"
        row-key="category_id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="分类名称" min-width="200" />
        <el-table-column prop="level" label="层级" width="80" align="center" />
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleAdd(row)">添加子分类</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button :type="row.status ? 'danger' : 'success'" link @click="handleStatus(row)">
              {{ row.status ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级分类">
          <el-cascader
            v-model="form.parent_id"
            :options="categoryOptions"
            :props="{ checkStrictly: true, value: 'category_id', label: 'name' }"
            clearable
            placeholder="请选择上级分类"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入图标" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 查询参数
const queryParams = reactive({
  name: '',
  status: ''
})

// 数据列表
const loading = ref(false)
const categoryList = ref([])
const categoryOptions = ref([])

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = reactive({
  category_id: undefined,
  parent_id: undefined,
  name: '',
  sort: 0,
  icon: '',
  description: ''
})

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}

// 获取分类列表
const getList = async () => {
  loading.value = true
  try {
    const { data } = await request.get('/product-category/list', { params: queryParams })
    categoryList.value = data.list
    // 构建分类选项，过滤掉禁用的分类
    categoryOptions.value = JSON.parse(JSON.stringify(data.list))
      .filter(item => item.status === 1)
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.name = ''
  queryParams.status = ''
  handleSearch()
}

// 新增分类
const handleAdd = (row) => {
  dialogTitle.value = row ? '新增子分类' : '新增分类'
  form.category_id = undefined
  form.parent_id = row ? row.category_id : undefined
  form.name = ''
  form.sort = 0
  form.icon = ''
  form.description = ''
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  dialogTitle.value = '编辑分类'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return

    try {
      const url = form.category_id ? '/product-category/edit' : '/product-category/add'
      await request.post(url, form)
      ElMessage.success(form.category_id ? '编辑成功' : '新增成功')
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('提交失败:', error)
    }
  })
}

// 删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该分类吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await request.post('/product-category/delete', {
        category_id: row.category_id
      })
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 更新状态
const handleStatus = async (row) => {
  try {
    await request.post('/product-category/status', {
      category_id: row.category_id,
      status: row.status ? 0 : 1
    })
    ElMessage.success('状态更新成功')
    getList()
  } catch (error) {
    console.error('更新状态失败:', error)
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-wrapper {
    margin-bottom: 20px;
  }
}
</style>